/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Frame.java
 *
 * Created on 9 mars 2010, 15:15:44
 */

package testmultinxt;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import lejos.nxt.remote.NXTCommand;
import lejos.nxt.remote.RemoteBattery;
import lejos.nxt.remote.RemoteMotor;
import lejos.pc.comm.NXTComm;
import lejos.pc.comm.NXTCommException;
import lejos.pc.comm.NXTCommFactory;
import lejos.pc.comm.NXTInfo;

/**
 *
 * @author Alan
 */
public class Frame extends javax.swing.JFrame {

    private NXTInfo[] nxts = null;
    private NXTComm nxtComm = null;


    /** Creates new form Frame */
    public Frame() throws NXTCommException {
        initComponents();
        this.nxtComm = NXTCommFactory.createNXTComm(NXTCommFactory.BLUETOOTH);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        nxtList = new java.awt.List();
        batteryButton = new javax.swing.JButton();
        startMButton = new javax.swing.JButton();
        stopMButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        textField = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Search NXTs");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        nxtList.setMultipleMode(true);

        batteryButton.setText("Récupérer les niveaux de batterie");
        batteryButton.setEnabled(false);
        batteryButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                batteryButtonActionPerformed(evt);
            }
        });

        startMButton.setText("Démarrer moteurs");
        startMButton.setEnabled(false);
        startMButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startMButtonActionPerformed(evt);
            }
        });

        stopMButton.setText("Arrêter moteurs");
        stopMButton.setEnabled(false);
        stopMButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stopMButtonActionPerformed(evt);
            }
        });

        textField.setColumns(20);
        textField.setRows(5);
        jScrollPane1.setViewportView(textField);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(nxtList, javax.swing.GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE)
                    .addComponent(batteryButton, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(startMButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(stopMButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(batteryButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(startMButton)
                            .addComponent(stopMButton)))
                    .addComponent(nxtList, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            this.nxtList.removeAll();
            this.nxtList.add("...");
            this.batteryButton.setEnabled(false);
            this.textField.setEnabled(false);
            this.startMButton.setEnabled(false);
            this.stopMButton.setEnabled(false);

            // crée un objet nxtComm utilisé pour la connexion à un NXT
            NXTComm nxtComm = NXTCommFactory.createNXTComm(NXTCommFactory.BLUETOOTH);

            // demande de faire une recherche des NXTs allumés aux alentour
            nxts = nxtComm.search(null, NXTCommFactory.BLUETOOTH);

            // fin recherche
            this.nxtList.removeAll();
            
            if (nxts.length < 1) {
                // aucun NXT trouvé
                this.nxtList.add("Aucun NXT trouvé.");
            } else {
                for (int i = 0; i < nxts.length; i++) {
                    this.nxtList.add(nxts[i].name);
                }
                this.batteryButton.setEnabled(true);
                this.textField.setEnabled(true);
                this.startMButton.setEnabled(true);
                this.stopMButton.setEnabled(true);
            }
            
        } catch (NXTCommException ex) {
            System.err.println(ex);
        }

    }//GEN-LAST:event_jButton1ActionPerformed

    private void batteryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_batteryButtonActionPerformed
        int[] selectedNXTs = this.nxtList.getSelectedIndexes();

        for (int i = 0; i < selectedNXTs.length; i++) {
            try {
                if (nxtComm.open(nxts[selectedNXTs[i]])) {
                    NXTCommand command = new NXTCommand();
                    command.setNXTComm(nxtComm);
                    RemoteBattery battery = new RemoteBattery(command);
                    this.textField.setText(this.textField.getText() + "\n" +
                            this.nxtList.getItem(selectedNXTs[i]) + " : " + battery.getVoltage() + " V");
                    command.close();
                    nxtComm.close();
                } else {
                    this.textField.setText(this.textField.getText() + "\n" +
                                    "Echec connexion à " + this.nxtList.getItem(selectedNXTs[i]) + ".");
                }
            } catch (Exception ex) {
                this.textField.setText(this.textField.getText() + "\n" + ex);
            }
        }
    }//GEN-LAST:event_batteryButtonActionPerformed

    private void startMButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startMButtonActionPerformed
        int[] selectedNXTs = this.nxtList.getSelectedIndexes();

        for (int i = 0; i < selectedNXTs.length; i++) {
            try {
                if (nxtComm.open(nxts[selectedNXTs[i]])) {
                    NXTCommand command = new NXTCommand();
                    command.setNXTComm(nxtComm);
                    RemoteMotor motor1 = new RemoteMotor(command, 1);
                    RemoteMotor motor2 = new RemoteMotor(command, 2);
                    motor1.forward();
                    motor2.forward();
                    this.textField.setText(this.textField.getText() + "\n" +
                            this.nxtList.getItem(selectedNXTs[i]) + " : moteurs lancés.");
                    command.close();
                    nxtComm.close();
                } else {
                    this.textField.setText(this.textField.getText() + "\n" +
                                    "Echec connexion à " + this.nxtList.getItem(selectedNXTs[i]) + ".");
                }
            } catch (Exception ex) {
                this.textField.setText(this.textField.getText() + "\n" + ex);
            }
        }
    }//GEN-LAST:event_startMButtonActionPerformed

    private void stopMButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopMButtonActionPerformed
        int[] selectedNXTs = this.nxtList.getSelectedIndexes();

        for (int i = 0; i < selectedNXTs.length; i++) {
            try {
                if (nxtComm.open(nxts[selectedNXTs[i]])) {
                    NXTCommand command = new NXTCommand();
                    command.setNXTComm(nxtComm);
                    RemoteMotor motor1 = new RemoteMotor(command, 1);
                    RemoteMotor motor2 = new RemoteMotor(command, 2);
                    motor1.stop();
                    motor2.stop();
                    this.textField.setText(this.textField.getText() + "\n" +
                            this.nxtList.getItem(selectedNXTs[i]) + " : moteurs arrêtés.");
                    command.close();
                    nxtComm.close();
                } else {
                    this.textField.setText(this.textField.getText() + "\n" +
                                    "Echec connexion à " + this.nxtList.getItem(selectedNXTs[i]) + ".");
                }
            } catch (Exception ex) {
                this.textField.setText(this.textField.getText() + "\n" + ex);
            }
        }
    }//GEN-LAST:event_stopMButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton batteryButton;
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private java.awt.List nxtList;
    private javax.swing.JButton startMButton;
    private javax.swing.JButton stopMButton;
    private javax.swing.JTextArea textField;
    // End of variables declaration//GEN-END:variables

}
